Haskell Basic Grammars
Table of Contents
1. Scoped Variables
We can use let ... in or where ... to bind temporary variables or functions, where statement can be positioned after body whilst let in should be positioned before the body.
solve :: Int -> Int -> [Int] -> String
solve n m doors = do
case indices of
[] -> "Yes"
_ -> case end - start + 1 of
x | x <= m -> "Yes"
_ -> "No"
where
indices = elemIndices 1 doors
ends = last indices
start = head indices
2. Pattern Matching
2.1. Enumeration Matching
Use _ to indicate match all cases but ignore their value.
greet :: String -> String -> String
greet "Finland" name = "Hei, " ++ name
greet "Italy" name = "Ciao, " ++ name
greet "England" name = "How do you do, " ++ name
greet _ name = "Hello, " ++ name
2.2. Condition Guards
By adding | <condition> after a variable while pattern matching, we can do filtering. Use otherwise to represent all other conditions.
describe :: Int -> String
describe n
| n = 2 = "Two"
| even n = "Even"
| n == 3 = "Three"
| otherwise = "The number" ++ show n
We may also combine condition guards with enumeration matching.
2.3. case of
case of also pattern matching based on value.
case x of
value1 -> return_value1
value2 -> return_value2
But with condition guards, we can also pattern matching based on condition.
case x of
x | condition -> return_value1
_ -> return_value2